package cn.seamus.marksman.processor.impl;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.cookie.Cookie;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.util.Assert;

import cn.seamus.marksman.common.Constants;
import cn.seamus.marksman.common.MarksmanException;

/**
 * 
 * <p>
 * 购物车页面
 * </p>
 * 
 * @author zhengss
 * @version 0.0.1
 * @see
 */
public class CartPageProcessor extends AbstractProcessor {
    private static Log logger = LogFactory.getLog(CartPageProcessor.class);
    private String cartPageUrl;

    /*
     * (non-Javadoc)
     * 
     * @see
     * cn.seamus.marksman.processor.impl.AbstractProcessor#prepareNext(java.
     * util.Map)
     */
    @Override
    protected Map<String, Object> prepareNext(Map<String, Object> params) throws MarksmanException {
        // TODO Auto-generated method stub
        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * cn.seamus.marksman.processor.impl.AbstractProcessor#read(java.util.Map)
     */
    @Override
    protected ProcessResult read(Map<String, Object> requestParams) throws MarksmanException {
        logger.info("打开购物车开始");
        Assert.notNull(cartPageUrl);
        Assert.isTrue(StringUtils.isNotBlank(cartPageUrl));

        URL cartPageURL = null;

        try {
            cartPageURL = new URL(cartPageUrl);
        } catch (MalformedURLException e) {
            throw new MarksmanException("Cannot create cartPageURL: cartPageUrl=" + cartPageUrl, e);
        }

        logger.info("Cart page URL= " + cartPageURL.toString());
        logger.info("Connecting...");
        CloseableHttpResponse response = executeGet(cartPageURL, null);

        ProcessResult result = new ProcessResult();
        Map<String, Object> resMap = new HashMap<String, Object>();
        result.setParams(resMap);
        String actionUrl = null;
        String actionMethod = null;
        String province = "Shanghai";
        String quantity = null;
        Header[] cookies = null;
        String cart = null;
        try {

            String body = EntityUtils.toString(response.getEntity());

            Document doc = Jsoup.parse(body);

            Elements inputForm = doc.getElementsByAttributeValue("name", "checkoutFormRFH");

            actionUrl = inputForm.attr("action");
            actionMethod = inputForm.attr("method");

            Elements provinceSelected = doc.getElementById("selectNoteNode").select("option");
            province = provinceSelected.attr("value"); // Shanghai

            Elements quantityEles = doc.select(".input-small");
            quantity = quantityEles.attr("value");

            resMap.put(Constants.PARAM_KEY_ADDTOCART_ACTION_URL, actionUrl);
            resMap.put(Constants.PARAM_KEY_ADDTOCART_ACTION_METHOD, actionMethod);

            logger.info("actionUrl=" + actionUrl + ", method=" + actionMethod);

            cookies = response.getHeaders(Constants.HTTP_HEADER_SETCOOKIE);

            logger.info("打开购物车结束");
        } catch (IOException e) {
            throw new MarksmanException("Cannot parse  content", e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
            }
        }

        logger.info("提交购物车开始");

        // 提交购物车
        actionUrl = cartPageURL.getProtocol() + "://" + cartPageURL.getHost() + actionUrl;
        URL checkoutURL = null;
        try {
            checkoutURL = new URL(actionUrl);
        } catch (MalformedURLException e) {
            throw new MarksmanException("Cannot create checkoutURL: actionUrl=" + actionUrl, e);
        }

        province = "Shanghai";
        // 购买数量
        Map<String, Object> reqParams = new HashMap<String, Object>();
        reqParams.put(Constants.REQ_PARAM_NAME_CART_PROVINCE, province);
        reqParams.put(Constants.REQ_PARAM_NAME_CART_QUANTITY, quantity);
        // reqParams.put(Constants.MAP_KEY_COOKIES, cookies);

        if ("post".equalsIgnoreCase(actionMethod)) {
            response = executePost(checkoutURL, reqParams);
        } else {
            response = executeGet(checkoutURL, reqParams);
        }

        // 获得结果
        try {
            String shopId = null;

            Header[] headers = response.getHeaders("X-ShopId");
            if (headers.length > 0) {
                shopId = headers[0].getValue();
            }

            for (Cookie cookie : (List<Cookie>) reqParams.get(Constants.MAP_KEY_COOKIE)) {
                if (cookie.getName().equals("cart")) {
                    cart = cookie.getValue();
                }
            }

            logger.info("shopId=" + shopId + ", cart=" + cart);
            resMap.put(Constants.PARAM_KEY_CART, cart);
            resMap.put(Constants.PARAM_KEY_SHOPID, shopId);
            logger.info("提交购物车结束");
        } finally {
            try {
                response.close();
            } catch (IOException e) {
            }
        }

        return result;
    }

    public String getCartPageUrl() {
        return cartPageUrl;
    }

    public void setCartPageUrl(String cartPageUrl) {
        this.cartPageUrl = cartPageUrl;
    }

}
